"""
2022  B圈新版课程 | 邢不行
author: 邢不行
微信: xbx6660
"""
import base64
import hashlib
import hmac
import json
import time
from urllib import parse
import requests

from datetime import datetime
from 中性策略实盘.config import secret, webhook


def cal_timestamp_sign(secret):
    # 根据钉钉开发文档，修改推送消息的安全设置https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
    # 当前时间戳，单位是毫秒，与请求调用时间误差不能超过1小时
    # python3用int取整
    timestamp = int(round(time.time() * 1000))
    # 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
    secret_enc = bytes(secret.encode('utf-8'))
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = bytes(string_to_sign.encode('utf-8'))
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    # 得到最终的签名值
    sign = parse.quote_plus(base64.b64encode(hmac_code))
    return str(timestamp), str(sign)


def send_dingding_msg(content):
    try:
        msg = {
            "msgtype": "text",
            "text": {"content": datetime.now().strftime("%m-%d %H:%M:%S") + '\n' + content}
        }
        headers = {"Content-Type": "application/json;charset=utf-8"}
        # https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX
        timestamp, sign_str = cal_timestamp_sign(secret)
        url = 'https://oapi.dingtalk.com/robot/send?access_token=' + webhook + \
              '&timestamp=' + timestamp + '&sign=' + sign_str
        body = json.dumps(msg)
        requests.post(url, data=body, headers=headers, timeout=10)
        print('成功发送钉钉\n')
    except Exception as e:
        print(f"发送钉钉失败:{e}\n")


def send_dingding_msg_for_position(equity, position_df):
    dingding_msg = f'账户净值：{equity:8.2f}\n'
    if not position_df.empty:
        dingding_msg += f'当前持仓未实现盈亏：{position_df["持仓盈亏"].sum():8.2f}\n'
        dingding_msg += '策略持仓：\n'
        for index, row in position_df.reset_index().iterrows():
            if row['当前持仓量'] != 0:
                dingding_msg += row[['symbol', '当前持仓量', '均价', '持仓盈亏']].to_string()
                dingding_msg += '\n'
    send_dingding_msg(dingding_msg)


def send_dingding_msg_for_order(order_param, order_res):
    """
    发送下单信息到钉钉
    """
    dingding_msg = ''
    for _ in range(len(order_param)):
        dingding_msg += f'币种:{order_param[_]["symbol"]}\n'
        dingding_msg += f'方向:{"做多" if order_param[_]["side"] == "BUY" else "做空"}\n'
        dingding_msg += f'价格:{order_param[_]["price"]}\n'
        dingding_msg += f'数量:{order_param[_]["quantity"]}\n'

        if 'msg' in order_res[_].keys():
            dingding_msg += f'下单结果:{order_res[_]["msg"]}'
        else:
            dingding_msg += f'下单结果: 下单成功'

        dingding_msg += '\n' * 2

    send_dingding_msg(dingding_msg)


if __name__ == '__main__':
    send_dingding_msg('test')
